package com.ztools.mvp;


import android.content.Context;
import android.content.ContextWrapper;

import com.blankj.utilcode.util.LogUtils;
import com.ztools.base.BaseActivity;


/**
 * 用于V和P的绑定和解绑，防止内存泄露
 *
 * @param <V>
 */
public abstract class BasePresenter<V extends IView> implements IPresenter<V> {


    private V mView;


    /**
     * 获取View对象
     *
     * @return
     */
    protected V getView() {
        if (this.mView == null) {
            LogUtils.e("v can not be null");
        }
        return mView;
    }


    /**
     * 是否已经关联
     *
     * @return
     */
    public boolean isViewAttached() {
        return mView != null;
    }

    /**
     * 绑定View
     *
     * @param v
     */
    @Override
    public void onAttachView(V v) {
        this.mView = v;
    }

    /**
     * 销毁View
     */
    @Override
    public void onDetachView() {
        if (isViewAttached()) {
            this.mView = null;
        }
    }


    public BaseActivity getActivity() {
        Context context = getView().getContext();
        if (context == null) {
            throw new NullPointerException("====> Context 空指针异常");
        }
        while (!(context instanceof BaseActivity) && context instanceof ContextWrapper) {
            context = ((ContextWrapper) context).getBaseContext();
        }
        if (context instanceof BaseActivity) {
            return (BaseActivity) context;
        }
        throw new ClassCastException("====> Context 不能转换为 Activity.");
    }

    /**
     * 获取请求标签的前缀
     *
     * @return
     */
    public String getTag() {
        return this.getClass().getSimpleName() + "_";
    }
}
